package com.mjk.manager.task.type.sqlhttp.http.encry;

import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.mjk.common.base.constns.BeeCommonConstns;
import com.mjk.common.tools.gson.GsonUtils;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.util.StrUtils;
import org.apache.ibatis.scripting.xmltags.OgnlCache;


/**
 * http资源推送 加密接口
 * @author Administrator
 *
 */
public interface IHttpSyncEncry {
	/**
	 * 转化 请求参数
     */
	default List<String> getSyncParams(Map<String,Object> params,String template) {
		//从 template 里面获取 变量
        Pattern r = Pattern.compile(BeeCommonConstns.TEMPLATE_PARAMS_MATH);
		Matcher m = r.matcher(template);
		Map<Integer,String> tmps = new HashMap<>();
		while (m.find()) {
			String leftKey =  m.group(1);
			Pattern keyPattern = Pattern.compile(BeeCommonConstns.SET_PARAMS_LIST);
			Matcher key = keyPattern.matcher(leftKey);
			Object obj = OgnlCache.getValue(leftKey, params);
			String format = StrUtils.format(m.replaceAll(""));
			if(key.find()) {//如果是list
				if(obj instanceof List list) {
					List<Map<String,Object>> items = list;
					Integer index = 0;
					for(Map<String,Object> item : items) {
						String replace = ObjectUtils.isEmpty(item)?"\"\"": GsonUtils.bean2Json(item);
						if(tmps.containsKey(index)) {
							if(format.equals("{}")) {
								tmps.put(index,  replace);
							}else {
								tmps.put(index, tmps.get(index).replace(m.group(), Objects.requireNonNull(replace)));
							}
						}else {
                            if (format.equals("{}")) {
                                tmps.put(index, replace);
                            } else {
                                tmps.put(index, tmps.getOrDefault(-1, template).replace(m.group(), replace));
                            }
						}
						index++;
					}
				}
			}else {//否则都是OBJ
				String replace = ObjectUtils.isEmpty(obj)?"\"\"":GsonUtils.bean2Json(obj);
				if(tmps.size() > 0) {
					for(Entry<Integer,String> entry : tmps.entrySet()) {
						if(format.equals("{}")) {
							entry.setValue(replace);
						}else {
							entry.setValue(entry.getValue().replace(m.group(), Objects.requireNonNull(replace)));
						}
					}
				}else {
					if(format.equals("{}")) {
						tmps.put(-1, replace);
					}else {
						String tmp = template.replace(m.group(), Objects.requireNonNull(replace));
						tmps.put(-1, tmp);
					}
				}
			}
		}
		if(tmps.size()>1) {
			tmps.remove(-1);
		}
        return new ArrayList<>(tmps.values());
	}
	/**
	 * 转化请求头
     */
	default Map<String,String> getSyncHeader(Map<String,Object> params) {
		return new HashMap<>();
	}
}
